// 顶点着色器
const vertexShaderSource = `
    attribute vec2 aPosition;
    attribute vec2 aTexCoord;
    attribute float aSize;
    attribute vec2 aVelocity;
    uniform float uTime;
    varying vec2 vTexCoord;

    void main() {
        vec2 position = aPosition + aVelocity * uTime;
        // 循环雪花位置
        position = vec2(
            mod(position.x + 1.0, 2.0) - 1.0,
            mod(position.y + 1.0, 2.0) - 1.0
        );
        gl_Position = vec4(position, 0.0, 1.0);
        gl_PointSize = aSize;
        vTexCoord = aTexCoord;
    }
`;

// 片元着色器
const fragmentShaderSource = `
    precision mediump float;
    uniform sampler2D uSampler;
    varying vec2 vTexCoord;

    void main() {
        vec2 coord = gl_PointCoord;
        vec4 texColor = texture2D(uSampler, coord);
        if (texColor.a < 0.1) discard;
        gl_FragColor = texColor;
    }
`;

// 创建着色器
function createShader(gl, type, source) {
    const shader = gl.createShader(type);
    gl.shaderSource(shader, source);
    gl.compileShader(shader);

    if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
        console.error('着色器编译失败:', gl.getShaderInfoLog(shader));
        gl.deleteShader(shader);
        return null;
    }
    return shader;
}

// 创建雪花粒子数据
function createSnowflakes(count, isExplosion = false, clickPosition = null) {
    const positions = [];
    const velocities = [];
    const sizes = [];
    const texCoords = [];

    for (let i = 0; i < count; i++) {
        if (isExplosion && clickPosition) {
            // 爆发效果的初始位置
            positions.push(
                clickPosition[0],
                clickPosition[1]
            );
            // 爆发效果的随机速度
            const angle = Math.random() * Math.PI * 2;
            const speed = Math.random() * 0.02 + 0.01;
            velocities.push(
                Math.cos(angle) * speed,
                Math.sin(angle) * speed - 0.001 // 略微向下的重力
            );
        } else {
            // 普通雪花的随机位置
            positions.push(
                Math.random() * 2 - 1,
                Math.random() * 2 - 1
            );
            // 普通雪花的随机速度
            velocities.push(
                (Math.random() - 0.5) * 0.0005, // 减小水平方向的随机速度
                -Math.random() * 0.002 - 0.001  // 增加垂直方向的下落速度
            );
        }
        // 随机大小
        sizes.push(Math.random() * 10 + 5);
        // 纹理坐标（整个纹理）
        texCoords.push(0, 0, 1, 1);
    }

    return {
        positions: new Float32Array(positions),
        velocities: new Float32Array(velocities),
        sizes: new Float32Array(sizes),
        texCoords: new Float32Array(texCoords),
        count
    };
}

// 加载纹理
async function loadTexture(gl, url) {
    const texture = gl.createTexture();
    return new Promise((resolve, reject) => {
        const image = new Image();
        image.onload = () => {
            gl.bindTexture(gl.TEXTURE_2D, texture);
            gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, image);
            gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
            gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
            gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
            resolve(texture);
        };
        image.onerror = reject;
        image.src = url;
    });
}

// 初始化WebGL
async function initWebGL() {
    const canvas = document.createElement('canvas');
    canvas.width = window.innerWidth;
    canvas.height = window.innerHeight;
    document.getElementById('app').appendChild(canvas);

    const gl = canvas.getContext('webgl');
    if (!gl) {
        console.error('WebGL不可用');
        return;
    }

    // 创建着色器程序
    const vertexShader = createShader(gl, gl.VERTEX_SHADER, vertexShaderSource);
    const fragmentShader = createShader(gl, gl.FRAGMENT_SHADER, fragmentShaderSource);
    const program = gl.createProgram();
    gl.attachShader(program, vertexShader);
    gl.attachShader(program, fragmentShader);
    gl.linkProgram(program);
    gl.useProgram(program);

    // 获取着色器变量位置
    const aPosition = gl.getAttribLocation(program, 'aPosition');
    const aTexCoord = gl.getAttribLocation(program, 'aTexCoord');
    const aSize = gl.getAttribLocation(program, 'aSize');
    const aVelocity = gl.getAttribLocation(program, 'aVelocity');
    const uTime = gl.getUniformLocation(program, 'uTime');

    // 创建初始雪花
    let snowflakes = createSnowflakes(100);

    // 创建缓冲区
    const positionBuffer = gl.createBuffer();
    const texCoordBuffer = gl.createBuffer();
    const sizeBuffer = gl.createBuffer();
    const velocityBuffer = gl.createBuffer();

    // 加载雪花纹理
    await loadTexture(gl, '/xa.png');

    // 启用混合
    gl.enable(gl.BLEND);
    gl.blendFunc(gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA);

    // 监听点击事件
    canvas.addEventListener('click', (event) => {
        const rect = canvas.getBoundingClientRect();
        const x = ((event.clientX - rect.left) / canvas.width) * 2 - 1;
        const y = -((event.clientY - rect.top) / canvas.height) * 2 + 1;
        
        // 创建爆发效果的雪花
        const explosionSnowflakes = createSnowflakes(20, true, [x, y]);
        
        // 合并新的雪花数据到现有数组
        const newPositions = new Float32Array([...snowflakes.positions, ...explosionSnowflakes.positions]);
        const newVelocities = new Float32Array([...snowflakes.velocities, ...explosionSnowflakes.velocities]);
        const newSizes = new Float32Array([...snowflakes.sizes, ...explosionSnowflakes.sizes]);
        const newTexCoords = new Float32Array([...snowflakes.texCoords, ...explosionSnowflakes.texCoords]);
        
        snowflakes = {
            positions: newPositions,
            velocities: newVelocities,
            sizes: newSizes,
            texCoords: newTexCoords,
            count: snowflakes.count + explosionSnowflakes.count
        };
    });

    let startTime = Date.now();

    // 渲染循环
    function render() {
        const currentTime = (Date.now() - startTime) / 1000;

        gl.viewport(0, 0, canvas.width, canvas.height);
        gl.clearColor(0.0, 0.0, 0.0, 1.0);
        gl.clear(gl.COLOR_BUFFER_BIT);

        // 更新缓冲区数据
        gl.bindBuffer(gl.ARRAY_BUFFER, positionBuffer);
        gl.bufferData(gl.ARRAY_BUFFER, snowflakes.positions, gl.STATIC_DRAW);
        gl.vertexAttribPointer(aPosition, 2, gl.FLOAT, false, 0, 0);
        gl.enableVertexAttribArray(aPosition);

        gl.bindBuffer(gl.ARRAY_BUFFER, texCoordBuffer);
        gl.bufferData(gl.ARRAY_BUFFER, snowflakes.texCoords, gl.STATIC_DRAW);
        gl.vertexAttribPointer(aTexCoord, 2, gl.FLOAT, false, 0, 0);
        gl.enableVertexAttribArray(aTexCoord);

        gl.bindBuffer(gl.ARRAY_BUFFER, sizeBuffer);
        gl.bufferData(gl.ARRAY_BUFFER, snowflakes.sizes, gl.STATIC_DRAW);
        gl.vertexAttribPointer(aSize, 1, gl.FLOAT, false, 0, 0);
        gl.enableVertexAttribArray(aSize);

        gl.bindBuffer(gl.ARRAY_BUFFER, velocityBuffer);
        gl.bufferData(gl.ARRAY_BUFFER, snowflakes.velocities, gl.STATIC_DRAW);
        gl.vertexAttribPointer(aVelocity, 2, gl.FLOAT, false, 0, 0);
        gl.enableVertexAttribArray(aVelocity);

        // 更新时间uniform
        gl.uniform1f(uTime, currentTime);

        // 绘制雪花
        gl.drawArrays(gl.POINTS, 0, snowflakes.count);

        requestAnimationFrame(render);
    }

    render();
}

// 页面加载完成后初始化WebGL
window.onload = initWebGL;